package cn.wolfcode.wolf2w.service.impl;


import cn.wolfcode.wolf2w.domain.${capitalize};
import cn.wolfcode.wolf2w.query.${capitalize}QueryObject;
import cn.wolfcode.wolf2w.repository.${capitalize}Repository;
import cn.wolfcode.wolf2w.service.I${capitalize}Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
//@Transactional mongodb事务必须复制集方式
public class ${capitalize}ServiceImpl implements I${capitalize}Service {
    @Autowired
    private ${capitalize}Repository repository;
    @Autowired
    private MongoTemplate template;
    @Override
    public void save(${capitalize} ${uncapitalize}) {
        ${uncapitalize}.setId(null);//防止游标
        repository.save(${uncapitalize});
    }

    @Override
    public void update(${capitalize} ${uncapitalize}) {
        repository.save(${uncapitalize});
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public ${capitalize} get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<${capitalize}> list() {
    return repository.findAll();
    }

    @Override
    public Page<${capitalize}> query(${capitalize}QueryObject qo) {
        //查询的条件对象
        Query query=new Query();
        //拼接条件
        long count = template.count(query, ${capitalize}.class);//计算一共有多少条数据 query 为无条件 totalCount  集合MOngoDb
        if (count==0){
        return Page.empty();//空的页面对象
        }
        //分页加排序---->条件拼接
        PageRequest pageRequest = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        //把条件放入查询对象中
        query.with(pageRequest);
        //查询当前结果集template.find
        List<${capitalize}> list = template.find(query, ${capitalize}.class);
            //PageImpl等价于之前的PageResult
            return new PageImpl<>(list,pageRequest,count);//PageResult原生的  pageRequest当前页  多少条数
            //PageHadler  分页插件的
            } 
}